package service

import (
	"github.com/cn-ygf/go-admin/internal/modular/system/dao"
	"github.com/cn-ygf/go-admin/internal/modular/system/model"
	"github.com/cn-ygf/go-admin/internal/modular/system/vo"
)

var (
	NoticeService = new(noticeService)
)

// noticeService 系统公告
type noticeService struct {
}

func (s *noticeService) GetList() ([]*model.SysNotice, error) {
	return dao.SysNotice.Find()
}

// QueryList 分页查询系统公告列表
func (s *noticeService) QueryList(req *vo.QueryNoticeListReq) ([]*model.SysNotice, int64, error) {
	var (
		u = dao.SysNotice
		d = u.Where()
	)
	if req.PageSize < 1 {
		req.PageSize = 10
	}
	if req.PageNum < 1 {
		req.PageNum = 1
	}
	if req.NoticeTitle != "" {
		d = d.Where(u.NoticeTitle.Like("%" + req.NoticeTitle + "%"))
	}
	if req.NoticeType != "" {
		d = d.Where(u.NoticeType.Eq(req.NoticeType))
	}
	return d.FindByPage((req.PageNum-1)*req.PageSize, req.PageSize)
}

// All 查询所有系统公告
func (s *noticeService) All() ([]*model.SysNotice, error) {
	return dao.SysNotice.Find()
}

// GetByID 根据id查询系统公告
func (s *noticeService) GetByID(id int32) (*model.SysNotice, error) {
	return dao.SysNotice.Where(dao.SysNotice.NoticeID.Eq(id)).First()
}

// GetByNoticeTitle 根据系统公告名查询
// noticeTitle 公告名称
func (s *noticeService) GetByNoticeTitle(noticeTitle string) (*model.SysNotice, error) {
	return dao.SysNotice.Where(dao.SysNotice.NoticeTitle.Eq(noticeTitle)).First()
}

// Add 添加系统公告
func (s *noticeService) Add(req *vo.AddNoticeReq) error {
	u := dao.SysNotice
	newConfig := &model.SysNotice{
		NoticeTitle:   req.NoticeTitle,
		NoticeContent: req.NoticeContent,
		NoticeType:    req.NoticeType,
		CreateBy:      req.CreateBy,
		Remark:        req.Remark,
	}
	err := u.Create(newConfig)
	if err != nil {
		systemLog.Errorln(err.Error())
		return ServerError
	}
	return nil
}

// Update 修改系统公告
func (s *noticeService) Update(req *vo.EditNoticeReq) error {
	u := dao.SysNotice
	_, err := u.Where(u.NoticeID.Eq(req.NoticeId)).Updates(map[string]any{
		u.NoticeTitle.ColumnName().String():   req.NoticeTitle,
		u.NoticeContent.ColumnName().String(): req.NoticeContent,
		u.NoticeType.ColumnName().String():    req.NoticeType,
		u.UpdateBy.ColumnName().String():      req.UpdateBy,
	})
	if err != nil {
		systemLog.Errorln(err.Error())
		return ServerError
	}
	return nil
}

// Delete 删除系统公告
func (s *noticeService) Delete(ids []int32) error {
	_, err := dao.SysNotice.Where(dao.SysNotice.NoticeID.In(ids...)).Delete()
	return err
}
